﻿var only = true; // 判断表格字段隐藏的只加载一次
var app = window.app || {};

var userApp = localStorage.user;




if (typeof userApp == "string") {
    userApp = JSON.parse(userApp);
}

if (userApp) {
    $.extend(app, userApp);
}

$.extend(app, {
    appId: 146,
    //url: "http://192.168.6.100:3000/new/三和代码/sanhe/data/"
    url: "http://47.106.146.13:806/api",
    h5Url:"http://47.106.146.13:81/h5/recruit_xp.html"
    //h5Url:"localhost:3000/new/三和H5/recruit_xp.html"
});

$.extend(app, {
    msg: function (text) {
        layer.msg(text, { icon: 1, anim: 0, offset: "80px" });
    },
    errMsg: function (text) {
        layer.msg(text, { icon: 2, anim: 6, offset: "80px" });
    },
    confirm: function (text, callback) {
        var layerId = layer.confirm(text, { icon: 3, btn: ["确定", "取消"], title: "操作提示", anim: 0/*, offset: "80px"*/ },
            function () {
                callback();
                layer.close(layerId);
            }, function () {
                layer.close(layerId);
            });
    },
    alert: function (text) {
        layer.alert(text, {
            icon: 0,
            title: "操作提示",
            anim: 0
        });
    },
    choose: function (text, config) {
        var cfg = {
            icon: 0,
            btn: [],
            title: "操作提示",
            anim: 0
        };

        var index = 1;

        for (var item in config) {
            cfg.btn.push(item);
            cfg["btn" + index] = config[item];
            ++index;
        }

        var oldBtn1 = cfg.btn1;

        cfg.btn1 = function () {
            oldBtn1();
            layer.close(layerId);
        };

        var layerId = layer.confirm(text, cfg);
    },
    tips: function (element, text) {
        function ShowTips() {
            if (element.jquery) {
                element = element[0];
            }

            var rect = element.getBoundingClientRect();

            if (rect.left <= 0 || rect.top <= 0 || rect.right >= $(window).width() || rect.bottom >= $(window).height()) {
                app.errMsg(text);

                return;
            }

            layer.tips(text, element, {
                tips: [2, '#f33'],
                anim: 6,
                tipsMore: true
            });
        }
        setTimeout(ShowTips, 1);
    },
    showPhoto: function (url) {
        var box = $("<div class=\"hide-img-box\"></div>");
        var img = $("<img />");

        var id = String(parseInt(Math.random() * 100000));

        img.attr("src", url);

        box.append(img);
        $(document.body).append(box);

        layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            // area: ['80%', '80%'],
            skin: 'layui-layer-nobg img-box',
            shadeClose: true,
            content: box
        });
    }
});

//缓存数据
var store = {
    save : function(name,value){
      localStorage.setItem(name,JSON.stringify(value));
    },
    fetch:function(value){
      return JSON.parse(localStorage.getItem(value)) || [];
    },
    remove : function(name){
        localStorage.removeItem(name);
    },
    clear : function(){
         localStorage.clear();
    }
}

//没登录调到登录页面
reLoadFn();
function reLoadFn( ){
	var obj = store.fetch('user');
	var arr = location.href.split('/');
    var newHtml = arr[arr.length-1];
	var re = /^login.html$/gi; //排除登录页面
	if( !obj.userName && !re.test(newHtml) ){ //没有登录就要跳
        store.remove('user');
		location.href = 'login.html';
	}
}
//重新加载ajax
function reAjax( rData ,fn){
	rData.Time = new Date().toISOString();
	
	rData.UserId = app.userId;
    rData.Token = app.token;
	rData.AppId = 1530 ;

	 var def = $.ajax({
         url: app.url,
         type:'post',
         beforeSend: function(jqXHR, settings){
            jqXHR.setRequestHeader("Content-Type","Json");
         },
         data:JSON.stringify( rData),
         success: function (result) {
             if (typeof result == "string") {
                 result = JSON.parse(result);
             }
             if(result.code == 16){
                app.userId = null; 
                app.userName = null;
                app.token = null;
                app.nickname = null;
                app.roleId = null;
                app.roleName = null;
                store.remove('user',app);
               
                location.href = 'login.html';
             }
             fn && fn(result);
         }
     });

     return def;
}


//渲染表格

/**
	table 表格对象
	tId  表格容器id
	wData 请求参数   var wData = {
            Command: "ReadPagingData",
            TableName: "Templates"
        }
	headArr 表格数组 一维数组 headArr = [
                {field:'Id', title: 'ID', sort: true}
                ,{field:'Name', title: '模板名称'}
                ,{field:'CycleTime', title: '模板周期（秒）', sort: true}
                ,{field:'BeginTime',title: '开始时间'}
                ,{field:'EndTime', title: '结束时间'} 
                 ,{title: '操作',toolbar: '#barDemo'}
        ];
	fn  回调函数
**/

function renderTable(table,url,tId,wData,headArr,fn,seArr){
	 wData.Time = new Date().toISOString();
	 wData.UserId = app.userId;
	 wData.Token =  app.token;
	 wData.WithTotal =  wData.WithTotal === undefined?true:wData.WithTotal;
	 wData.Begin =  1;
     wData.End =  10;
	 wData.AppId  =  1530;

     var allArr = [];
     if( seArr ) {
         allArr.push(headArr);
         allArr.push(seArr);
     }else{
        allArr.push(headArr);
     }
     var countAll =0;
     var lArr = [10,20,30,40,50,60,70,80,99999];
     var configer = { //其它参数在此省略
           elem: tId,
           url:url,
           height:'full-140',
           where: wData,
           cols: allArr,
           page: true,
           even: true,
           done : function(res){
             if(res.code == 16){
               app.userId = null; 
               app.userName = null;
               app.token = null;
               app.nickname = null;
               app.roleId = null;
               app.roleName = null;
               store.remove('user',app);
               parent.location.href = 'login.html';
             }
             // countAll = res.count;
             // lArr.splice(lArr.length-1,1);
             // lArr.push(countAll);
             var option = $('.layui-laypage-limits').find('option');
             option.eq(lArr.length-1).text('全部');            
             fn && fn(res);
           },
           limits:lArr  
     }
    
    var ta = table.render(configer);
    setTimeout(function(){
        // lArr.splice(lArr.length-1,1);
        // lArr.push(getCount(countAll));
       
        // configer.limits = lArr;

        //$(".layui-laypage-btn").click();
        $('.layui-table-view').attr('id','lay_table');

        $('#lay_table span').each(function(i){
           if($(this).html() == '操作'){
             $(this).closest('th').attr('data-off','true');
           }
        });
    },200);
    return ta;

}

function getCount(countAll){
    return countAll;
}


function tabReload( tab ,allData ){
     for( var i in allData ) {
        if( !allData[i] || allData[i] == ''){
           delete allData[i];
           tab.reload('tableL',{
              where: allData
           });
           break;
        }else{
          layui.table.reload('tableL',{
             where: allData
          });
        }
    }

    $('.layui-table-view').attr('id','lay_table');

    $('#lay_table span').each(function(i){
       if($(this).html() == '操作'){
         $(this).closest('th').attr('data-off','true');
       }
    });
}


//检测是否 ie 浏览器

function IEVersion() {
   var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
   var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
   var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
   var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
   if(isIE || isEdge || isIE11) {
       // var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
       // reIE.test(userAgent);
       // var fIEVersion = parseFloat(RegExp["$1"]);
       // if(fIEVersion == 7) {
       //     return 7;
       // } else if(fIEVersion == 8) {
       //     return 8;
       // } else if(fIEVersion == 9) {
       //     return 9;
       // } else if(fIEVersion == 10) {
       //     return 10;
       // } else {
       //     return 6;//IE版本<=7
       // }   
       return true;
   } else{
       return false;//不是ie浏览器
   }
}
